package com.sinoglobal.sinostore.adapter;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.LogUtils;
import com.sinoglobal.sinostore.R;
import com.sinoglobal.sinostore.activity.AddCommentActivity;
import com.sinoglobal.sinostore.activity.PayforActivity;
import com.sinoglobal.sinostore.bean.BaseVo;
import com.sinoglobal.sinostore.bean.OrderVo;
import com.sinoglobal.sinostore.bean.ServiceTelVo;
import com.sinoglobal.sinostore.dialog.RefundDialog;
import com.sinoglobal.sinostore.dialog.RefundDialog.Listener;
import com.sinoglobal.sinostore.dialog.SweetAlertDialog;
import com.sinoglobal.sinostore.dialog.SweetAlertDialog.OnSweetClickListener;
import com.sinoglobal.sinostore.listener.OnAntiViolenceClickListener;
import com.sinoglobal.sinostore.service.OrderManager;
import com.sinoglobal.sinostore.service.OrderManager.OrderOperationCallBack;
import com.sinoglobal.sinostore.system.Constants;
import com.sinoglobal.sinostore.utils.BitmapHelp;
import com.sinoglobal.sinostore.utils.TextUtil;

public class OrderAdapter extends AbBaseAdapter<OrderVo> {

	private BitmapUtils  bitmapUtils;
	private SweetAlertDialog sweetAlertDialog;
	private RefundDialog refundDialog;
	
	//支付方式
	private int payType;
	
	public OrderAdapter(Context context, List<OrderVo> data) {
		super(context, R.layout.shop_order_list_item, data);
		bitmapUtils = BitmapHelp.getBitmapUtils(context);
		sweetAlertDialog=new SweetAlertDialog(context);
		refundDialog=new RefundDialog(context);
		loadTelNum();
	}
	@Override
	void setView(final int position, View convertView) {
		final OrderVo orderVo=getItem(position);

		TextView tvCreateTime= ViewHolder.getViewById(convertView, R.id.create_time);
		tvCreateTime.setText("下单时间："+orderVo.getCreate_time());

		TextView tvGoodsName= ViewHolder.getViewById(convertView, R.id.goods_name);
		tvGoodsName.setText(orderVo.getGoods_name());

		TextView tvGoodsNum= ViewHolder.getViewById(convertView, R.id.goods_nums);
		tvGoodsNum.setText("数量：x"+orderVo.getGoods_nums());

		ImageView ivPic= ViewHolder.getViewById(convertView, R.id.ivGoods);
		bitmapUtils.display(ivPic,orderVo.getImg_url());
		TextView tvGoodsState= ViewHolder.getViewById(convertView, R.id.status);

		TextView tvFreight= ViewHolder.getViewById(convertView, R.id.freight);
		tvFreight.setVisibility(View.GONE);

		TextView tvInviteTime= ViewHolder.getViewById(convertView, R.id.invite);
		tvInviteTime.setVisibility(View.GONE);

		TextView tvRedBtn= ViewHolder.getViewById(convertView, R.id.tvRedBtn);
		tvRedBtn.setVisibility(View.GONE);

		TextView tvGrayBtn= ViewHolder.getViewById(convertView, R.id.tvCancel);
		tvGrayBtn.setVisibility(View.GONE);
		if(Constants.PHYSICAL.equals(orderVo.getType()) && Constants.KUAIDI.equals(orderVo.getDraw_type())){//实物
			tvFreight.setText(String.format("运费：%s元", orderVo.getFreight()));
			tvFreight.setVisibility(View.VISIBLE);
		}
		switch (Integer.parseInt(orderVo.getStatus())) {
		case Constants.UNPAID_CODE://未付款
			tvGoodsState.setText("待付款");
			tvGrayBtn.setText("取消订单");
			tvGrayBtn.setVisibility(View.VISIBLE);
			tvRedBtn.setVisibility(View.VISIBLE);
			tvRedBtn.setText("支付");
			break;
		case Constants.UNFILLEDORDER_CODE://未发货+未领取（支付完成）+未使用（虚拟商品）
			if(Constants.VIRTUALGOODS.equals(orderVo.getType())){//虚拟商品
				tvGoodsState.setText("未使用");
				tvGrayBtn.setVisibility(View.VISIBLE);
				tvGrayBtn.setText("申请退款");
				tvInviteTime.setText(String.format("有效期：%s至%s", orderVo.getUse_start_time(),orderVo.getUse_end_time()));
				tvInviteTime.setVisibility(View.VISIBLE);
			}else{
				if(Constants.ZIQU.equals(orderVo.getDraw_type())){//自取商品
					tvGoodsState.setText("未领取");
					tvGrayBtn.setVisibility(View.VISIBLE);
					tvGrayBtn.setText("申请退款");
					
					tvInviteTime.setText(String.format("有效期至：%s", orderVo.getInvite()));
					tvInviteTime.setVisibility(View.VISIBLE);
				}else{
					tvGoodsState.setText("待发货");
					tvGrayBtn.setVisibility(View.VISIBLE);
					tvGrayBtn.setText("申请退款");
				}
			}
			break;
		case Constants.SHIPPED_CODE://已发货
			tvGoodsState.setText("已发货");
			tvGrayBtn.setVisibility(View.VISIBLE);
			tvRedBtn.setVisibility(View.VISIBLE);
			tvGrayBtn.setText("申请退款");
			tvRedBtn.setText("确认收货");
			tvInviteTime.setText(String.format("自动收货时间：\n%s", orderVo.getEnd_receipt()));
			tvInviteTime.setVisibility(View.VISIBLE);
			break;
		case Constants.TAKEGOODS_CODE://已收货+已领取+已使用（待评价）
			if(Constants.VIRTUALGOODS.equals(orderVo.getType())){//虚拟商品
				tvGoodsState.setText("已使用");
				tvRedBtn.setVisibility(View.VISIBLE);
				tvRedBtn.setText("评价");
				tvInviteTime.setText(String.format("有效期：%s至%s", orderVo.getUse_start_time(),orderVo.getUse_end_time()));
				tvInviteTime.setVisibility(View.VISIBLE);
			}else{
				if(Constants.ZIQU.equals(orderVo.getDraw_type())){
					tvGoodsState.setText("已领取");
				}else{
					tvGoodsState.setText("待评价");
				}
				tvGrayBtn.setText("申请退款");
				tvGrayBtn.setVisibility(View.VISIBLE);
				tvRedBtn.setVisibility(View.VISIBLE);
				tvRedBtn.setText("评价");
			}
			break;
		case Constants.FINISH_CODE://已完成
			tvGoodsState.setText("已完成");
			tvRedBtn.setVisibility(View.VISIBLE);
			tvRedBtn.setText("删除订单");
			tvGrayBtn.setVisibility(View.VISIBLE);
			tvGrayBtn.setText("申请退款");
			break;
		case Constants.CANCEL_CODE://已取消
			tvGoodsState.setText("已取消");
			tvRedBtn.setVisibility(View.VISIBLE);
			tvRedBtn.setText("删除订单");
			break;
		case Constants.PAST_CODE://已过期
			tvGoodsState.setText("已过期");
			tvRedBtn.setVisibility(View.VISIBLE);
			tvRedBtn.setText("删除订单");
			tvGrayBtn.setVisibility(View.VISIBLE);
			tvGrayBtn.setText("申请退款");
			if(Constants.VIRTUALGOODS.equals(orderVo.getType())){
				tvInviteTime.setText(String.format("有效期：%s至%s", orderVo.getUse_start_time(),orderVo.getUse_end_time()));
				tvInviteTime.setVisibility(View.VISIBLE);
			}else{
				if(Constants.ZIQU == orderVo.getDraw_type()){
					tvInviteTime.setText(String.format("有效期至：%s", orderVo.getEnd_receipt()));
					tvInviteTime.setVisibility(View.VISIBLE);
				}
			}
			break;
		case Constants.CLOSE_CODE://已关闭
			tvGoodsState.setText("已关闭");
			tvRedBtn.setVisibility(View.VISIBLE);
			tvRedBtn.setText("删除订单");
			break;
		case Constants.EXCEPTION_CODE://
			tvGoodsState.setText("异常订单");
			tvRedBtn.setVisibility(View.INVISIBLE);
			tvGrayBtn.setVisibility(View.INVISIBLE);
			break;
		default:
			break;
		}
		
		LinearLayout llBtnZone= ViewHolder.getViewById(convertView, R.id.llBtnZone);
		llBtnZone.setVisibility(View.VISIBLE);

		TextView tvGoodsPrice= ViewHolder.getViewById(convertView, R.id.price);
		if(TextUtil.isZeroOrNull(orderVo.getPrice_pay()) && !TextUtil.isZeroOrNull(orderVo.getCash_pay())){//积分单价为零，现金不为零，为现金支付
			tvGoodsPrice.setText(String.format("单价：%s元", orderVo.getCash_pay()));
		}else if(TextUtil.isZeroOrNull(orderVo.getCash_pay()) && !TextUtil.isZeroOrNull(orderVo.getPrice_pay())){//现金单价为零，为积分支付
			tvGoodsPrice.setText(String.format("单价：%s%s", orderVo.getPrice_pay(),context.getString(R.string.score_unit)));
		}else{//两个都不为零则为现金加积分支付
			tvGoodsPrice.setText(String.format("单价：%s元+%s%s", orderVo.getCash_pay(),orderVo.getPrice_pay(),context.getString(R.string.score_unit)));
		}

		TextView tvGoodsSpendingTotal= ViewHolder.getViewById(convertView, R.id.spending_total);
		if(TextUtil.isZeroOrNull(orderVo.getSpending_total()) && !TextUtil.isZeroOrNull(orderVo.getCash_pay_total())){//积分总价为空,现金不为零，为现金支付
			double tPrice = Double.parseDouble(orderVo.getCash_pay_total());
			if(!TextUtil.isZeroOrNull(orderVo.getFreight())){
				tPrice+=Double.parseDouble(orderVo.getFreight());
			}
			tvGoodsSpendingTotal.setText(String.format("共计：%.2f元", tPrice));
		}else if(TextUtil.isZeroOrNull(orderVo.getCash_pay_total()) && !TextUtil.isZeroOrNull(orderVo.getSpending_total()) 
				&& TextUtil.isZeroOrNull(orderVo.getFreight())){//现金总价为空，积分不为空，为积分支付
			tvGoodsSpendingTotal.setText(String.format("共计：%s%s", orderVo.getSpending_total(),context.getString(R.string.score_unit)));
		}else{//
			double tPrice = Double.parseDouble(orderVo.getCash_pay_total());
			if(!TextUtil.isZeroOrNull(orderVo.getFreight())){
				tPrice+=Double.parseDouble(orderVo.getFreight());
			}
			tvGoodsSpendingTotal.setText(String.format("共计：%.2f元+%s%s", tPrice,orderVo.getSpending_total(),context.getString(R.string.score_unit)));
		}
		
		MyClickListener clickListener = new MyClickListener(position);
		tvRedBtn.setOnClickListener(clickListener);
		tvGrayBtn.setOnClickListener(clickListener);
		

	}
	
	/**反暴力点击**/
	private class MyClickListener extends OnAntiViolenceClickListener {
		private int position;

		public MyClickListener(int position) {
			this.position = position;
		}

		@Override
		public void onAVClick(View v) {
			final OrderVo orderVo = getItem(position);
			int id = v.getId();
			if (id == R.id.tvRedBtn) {
				switch (Integer.parseInt(orderVo.getStatus())) {
				case Constants.UNPAID_CODE:// 未支付
					gotoPay(orderVo);
					break;
				case Constants.SHIPPED_CODE:// 确认收货
					sweetAlertDialog.setTitleText("为确保商品准确送到您手中\n亲，您真的收到商品了吗").setCancelText("取消").showCancelButton(true)
							.setConfirmText("确定").setConfirmClickListener(new OnSweetClickListener() {
								@Override
								public void onClick(SweetAlertDialog sweetAlertDialog) {
									sweetAlertDialog.dismiss();
									confirmGoodsReceive(orderVo);
								}
							}).show();
					break;
				case Constants.TAKEGOODS_CODE:// 待评价
					addComment(orderVo, position);
					break;
				case Constants.FINISH_CODE:
				case Constants.CANCEL_CODE:
				case Constants.PAST_CODE:
				case Constants.CLOSE_CODE:
					sweetAlertDialog.setTitleText("确定要删除订单吗").setCancelText("取消").showCancelButton(true).setConfirmText("确定")
							.setConfirmClickListener(new OnSweetClickListener() {
								@Override
								public void onClick(SweetAlertDialog sweetAlertDialog) {
									sweetAlertDialog.dismiss();
									deleteOrder(orderVo);
								}
							}).show();
					break;
				default:
					break;
				}
			} else if (id == R.id.tvCancel) {
				switch (Integer.parseInt(orderVo.getStatus())) {
				case Constants.UNPAID_CODE:// 未支付
					sweetAlertDialog.setTitleText("确定要取消订单吗?").setCancelText("取消").showCancelButton(true).setConfirmText("确定")
							.setConfirmClickListener(new OnSweetClickListener() {
								@Override
								public void onClick(SweetAlertDialog sweetAlertDialog) {
									sweetAlertDialog.dismiss();
									cancelOrder(orderVo);
								}
							}).show();
					break;
				default:// 申请退款
					if (TextUtil.stringIsNotNull(Constants.serviceTel)) {
						refundDialog.show();
					}
					break;
				}
			} else {
			}

		}

	}
	
	
	
	//去支付页面
	protected void gotoPay(OrderVo orderVo) {
		Intent intent=new Intent(context,PayforActivity.class);
		intent.putExtra("goodsType", orderVo.getType());
		intent.putExtra("orderNum", orderVo.getOrder_num());
		intent.putExtra("goodsName", orderVo.getGoods_name());
		intent.putExtra("submitType", orderVo.getDraw_type());
		intent.putExtra("goodsImg", orderVo.getImg_url());
		if(TextUtil.isZeroOrNull(orderVo.getSpending_total()) && !TextUtil.isZeroOrNull(orderVo.getCash_pay_total())){//积分总价为空,现金不为零，为现金支付
			//现金支付
			payType = Constants.MONEYPAY;
		}else if(TextUtil.isZeroOrNull(orderVo.getCash_pay_total()) && !TextUtil.isZeroOrNull(orderVo.getSpending_total()) 
				&& TextUtil.isZeroOrNull(orderVo.getFreight())){//现金总价为空，积分不为空，为积分支付
			//现金支付
			payType = Constants.SCOREPAY;
		}else{//
			//现金支付
			payType = Constants.MONEYPAY;
		}
		intent.putExtra("payType", payType);
		context.startActivity(intent);
	}
	/**
	 * 
	 * @author zrh
	 * @methods addComment 
	 * @description 去评价
	 * @date 2015年1月16日 下午7:19:30
	 * @param orderVo
	 * @param position 参数说明
	 */
	protected void addComment(OrderVo orderVo, int position) {
		Intent intent=new Intent(context,AddCommentActivity.class);
		intent.putExtra(AddCommentActivity.ID, orderVo.getGoods_id());
		intent.putExtra(AddCommentActivity.TYPE, "1");
		intent.putExtra(AddCommentActivity.IMG_URL,orderVo.getImg_url());
		intent.putExtra(AddCommentActivity.NAME, orderVo.getGoods_name());
		intent.putExtra(AddCommentActivity.ORDER_NUM, orderVo.getOrder_num());
		intent.putExtra(AddCommentActivity.CASH_PAY, orderVo.getCash_pay());
		intent.putExtra(AddCommentActivity.PRICE_PAY, orderVo.getPrice_pay());
		((Activity) context).startActivityForResult(intent,0);
	}
	private void cancelOrder(final OrderVo orderVo) {
		final ProgressDialog progressDialog=new ProgressDialog(context);
		OrderManager orderManager=new OrderManager();
		orderManager.setCallBack(new OrderOperationCallBack() {

			@Override
			public void onSuccess(BaseVo baseVo) {
				notifyDataSetChanged();
			}

			@Override
			public void onRequestStart() {
				try {
					progressDialog.show();
				} catch (Exception e) {
				}
				
			}
			@Override
			public void onRequestComplete() {
				try {
					progressDialog.dismiss();
				} catch (Exception e) {
				}
			}
			@Override
			public void onFailure(BaseVo baseVo) {
				try {
					progressDialog.dismiss();
				} catch (Exception e) {
				}
				if (baseVo!=null) {
					Toast.makeText(context, baseVo.getMessage(), 0).show();
				}
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				try {
					progressDialog.dismiss();
				} catch (Exception e) {
				}
//				Toast.makeText(context, "获取数据失败:msg="+msg+"errorCode=="+error.getExceptionCode(), 0).show();
			}
		});
		orderManager.cancelOrder(orderVo);
	}
	private void deleteOrder(final OrderVo orderVo) {
		final ProgressDialog progressDialog=new ProgressDialog(context);
		OrderManager orderManager=new OrderManager();
		orderManager.setCallBack(new OrderOperationCallBack() {

			@Override
			public void onSuccess(BaseVo baseVo) {
				removeItem(orderVo);
			}
			@Override
			public void onRequestStart() {
				try {
					progressDialog.show();
				} catch (Exception e) {
				}
				
			}
			@Override
			public void onRequestComplete() {
				try {
					progressDialog.dismiss();
				} catch (Exception e) {
				}
				
			}
			@Override
			public void onFailure(BaseVo baseVo) {
				try {
					progressDialog.dismiss();
				} catch (Exception e) {
				}
				if (baseVo!=null) {
					Toast.makeText(context, baseVo.getMessage(), 0).show();
				}
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				progressDialog.dismiss();
//				Toast.makeText(context, "获取数据失败:msg="+msg+"errorCode=="+error.getExceptionCode(), 0).show();
			}
		});
		orderManager.deleteOrder(orderVo);
	}
	/**
	 * 
	 * @author zrh
	 * @methods confirmGoodsReceive 
	 * @description  确认收货
	 * @date 2015年1月16日 下午6:25:31 参数说明
	 */
	private void confirmGoodsReceive(final OrderVo orderVo) {
		final ProgressDialog progressDialog=new ProgressDialog(context);
		OrderManager orderManager=new OrderManager();
		orderManager.setCallBack(new OrderOperationCallBack() {
			@Override
			public void onSuccess(BaseVo baseVo) {
				notifyDataSetChanged();
			}
			@Override
			public void onRequestStart() {
				try {
					progressDialog.show();
				} catch (Exception e) {
				}
				
			}
			@Override
			public void onRequestComplete() {
				try {
					progressDialog.dismiss();
				} catch (Exception e) {
				}
				
			}
			@Override
			public void onFailure(BaseVo baseVo) {
				try {
					progressDialog.dismiss();
				} catch (Exception e) {
				}
				if (baseVo!=null) {
					Toast.makeText(context, baseVo.getMessage(), 0).show();
				}
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				progressDialog.dismiss();
			}
		});
		orderManager.confirmGoodsReceive(orderVo);
	}
	private void initRefundDialog() {
		refundDialog.setListener(new Listener() {

			@Override
			public void btnCallClick() {
				//跳到拨号界面  
				Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+Constants.serviceTel)); 
				context.startActivity(intent);
			}
		});
		refundDialog.setTellNum(Constants.serviceTel);
	}
	//加载客服电话
	private void loadTelNum() {
		if (TextUtil.stringIsNull(Constants.serviceTel)) {
			RequestParams params = new RequestParams();
			params.addQueryStringParameter("por", "208");
			params.addQueryStringParameter("proIden", Constants.STOREFLAG);
			HttpUtils http = new HttpUtils();
			http.send(HttpRequest.HttpMethod.POST,Constants.STORE_URL,params,
					new RequestCallBack<String>() {
				@Override
						public void onStart() {
							super.onStart();
						}
				@Override
				public void onLoading(long total, long current, boolean isUploading) {
				}
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					if (responseInfo!=null&&TextUtil.stringIsNotNull(responseInfo.result)) {
						LogUtils.e("responseInfo.result==>"+responseInfo.result);
						ServiceTelVo result=null;
						try {
							result = JSON.parseObject(responseInfo.result, ServiceTelVo.class);
						} catch (Exception e) {
							e.printStackTrace();
							Toast.makeText(context, "数据解析错误", 0).show();
							return;
						}
						Constants.serviceTel=result.getPhone();
						initRefundDialog();
					}
				}
				@Override
				public void onFailure(HttpException error, String msg) {
				}
			});
		}else{
			initRefundDialog();
		}
	}
}
